local require = require
local setmetatable = setmetatable
local error = error
local table = table
local ngx = ngx
local os = os
local string = string
local tonumber = tonumber
local pcall = pcall
local unpack = unpack
local math = math
local conf = require "conf"
local util = require "util"
local pairs = pairs
local order = require "order"
package.cpath = "/opt/xyitech/jieyan-backend-production/xbit/?.so"
local xbit = require 'xbit'
package.cpath = "/usr/nginx/?.so;;"
local json = require 'cjson'

module(...)
_VERSION = '0.1'
 _int32_t = 0
 _int16_t = 1
 _float = 2
 _uint32_t = 4
 _uint16_t = 5
 _uint8_t = 6
 _int8_t = 7
 _dynamic = 99

local _M = { _VERSION = '0.1' }


local mt = { __index = _M }

local function _getFirstLastKey(t, startAt)
    local firstKey, lastKey, length = nil, nil, 0
    for k,v in pairs(t) do
        if not startAt or (startAt and tonumber(k) >= startAt) then
            length = length + 1
            if not firstKey then
                firstKey = k
            end
            lastKey = k
        end
    end
    return firstKey, lastKey, length
end

local function init(plane, opt)
    if not opt.uid then
        opt.uid = 1
    end
    local user = conf.userDetail({["id"] = opt.uid})
    if opt.fid then
        plane.fid = opt.fid
    end
    if opt.orderId then
        local res, offset, logs = order.analyzeHtml(user, {["order_id"] = opt.orderId})
        -- ngx.log(ngx.ERR, json.encode(res))
        -- ngx.log(ngx.ERR, json.encode(offset))
        -- ngx.log(ngx.ERR, json.encode(logs))
        plane.logs = logs
        plane.firstKey, plane.lastKey, plane.logLength = _getFirstLastKey(logs, opt.startAt)
    end
    plane.index = 1
end

function _M.new(self, opts)
    local plane = {}
    init(plane, opts)
    return setmetatable({ plane = plane }, mt)
end


function _M.update(self, opts)
    self.plane.index = self.plane.index + 1

    if self.plane.index >= #self.plane then
        self = nil
    end

end

function _M.out(self)
    local plane = self.plane
    if not plane then
        return nil, "not initialized yet"
    end
    local res = {}
    local logs = self.plane.logs[self.plane.firstKey + self.plane.index] or {}
    for k,v in pairs(logs) do
        if self.plane.fid then
            v[2] = self.plane.fid
        end
        table.insert(res, v)
    end
    return res
end

return _M